/**
 * 微信支付 - 申请退款
 */
const cloud = require('wx-server-sdk');
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
});

// 云函数入口函数
exports.main = async (event, context) => {
    // 参数验证
    const {
        transaction_id,
        refund_amount,
        total_amount,
        refund_reason = '用户申请退款',

    } = event.data
    if (!transaction_id  || !refund_amount || !total_amount) {
        return {
          success: false,
          message: '缺少必要参数: transaction_id, refund_amount, total_amount'
        }
      }
  
      // 金额验证
      if (refund_amount <= 0 || total_amount <= 0 || refund_amount > total_amount) {
        return {
          success: false,
          message: '退款金额必须大于0且不超过原订单金额'
        }
      }
      const outRefundNo = `RF${Date.now()}${Math.floor(Math.random() * 1000)}` 
    const res = await cloud.callFunction({
        name: 'cloudbase_module',
        data: {
            name: 'wxpay_refund',
            data: {
                transaction_id: transaction_id, // 微信订单号
                out_refund_no: outRefundNo, // 商户内部退款单号
                amount: {
                    refund: refund_amount, // 退款金额
                    total: total_amount, // 原订单金额,
                    currency: 'CNY',
                },
                reason:refund_reason
            },
        },
    });
    console.log('退款结果',res);
    return res.result;
};